import React, { useState, useEffect } from 'react';
import { Upload, Button, message, Typography, Card, Alert, Image, Space, Divider, Progress } from 'antd';
import { UploadOutlined, InboxOutlined, EyeOutlined, DeleteOutlined, UserOutlined } from '@ant-design/icons';
import type { UploadFile, UploadProps } from 'antd/es/upload/interface';
import axios from 'axios';

const { Title, Text } = Typography;
const { Dragger } = Upload;

const FaceManagementPage: React.FC = () => {
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const [uploading, setUploading] = useState(false);
    const [uploadProgress, setUploadProgress] = useState(0);
    const [error, setError] = useState<string | null>(null);
    const [success, setSuccess] = useState<string | null>(null);
    const [previewImage, setPreviewImage] = useState<string | null>(null);
    const [currentFaceData, setCurrentFaceData] = useState<any>(null);
    const [loading, setLoading] = useState(false);

    // 获取当前用户的人脸数据
    const fetchCurrentFaceData = async () => {
        setLoading(true);
        const token = localStorage.getItem('authToken');

        try {
            // 添加时间戳防止缓存
            const timestamp = new Date().getTime();
            const response = await axios.get(`/api/faces/?t=${timestamp}`, {
                headers: {
                    'Authorization': `Token ${token}`,
                    'Cache-Control': 'no-cache',
                    'Pragma': 'no-cache'
                },
            });

            console.log('API响应原始数据:', response.data);

            // 由于现在使用OneToOneField，每个用户最多只有一条人脸数据
            if (response.data && response.data.length > 0) {
                const faceData = response.data[0];
                setCurrentFaceData(faceData);
                console.log('成功获取用户人脸数据:', faceData);
                console.log('UI状态已更新，当前人脸数据ID:', faceData.id);
            } else {
                setCurrentFaceData(null);
                console.log('用户暂无人脸数据');
            }
        } catch (err: any) {
            console.error('获取人脸数据失败:', err);
            // 如果是404错误（用户无人脸数据），这是正常情况
            if (err.response?.status === 404) {
                setCurrentFaceData(null);
            } else {
                // 其他错误需要显示给用户
                setError('获取人脸数据失败，请刷新页面重试');
            }
        } finally {
            setLoading(false);
        }
    };

    // 组件加载时获取当前人脸数据
    useEffect(() => {
        fetchCurrentFaceData();
    }, []);

    // 清除预览和文件
    const clearPreview = () => {
        setPreviewImage(null);
        setFileList([]);
        setError(null);
        setSuccess(null);
    };

    const handleUpload = async () => {
        if (fileList.length === 0) {
            message.error('请先选择一张图片！');
            return;
        }

        const file = fileList[0];
        // 修复：优先使用originFileObj，如果不存在则使用file本身
        let fileToUpload: File | null = null;

        if (file.originFileObj) {
            fileToUpload = file.originFileObj as File;
        } else if (file instanceof File) {
            fileToUpload = file;
        } else {
            // 最后的备选方案：从DOM获取文件
            const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
            if (fileInput && fileInput.files && fileInput.files.length > 0) {
                fileToUpload = fileInput.files[0];
            }
        }

        if (!fileToUpload) {
            message.error('无法获取文件，请重新选择。');
            return;
        }

        // 调试日志
        console.log('准备上传文件:', {
            fileName: fileToUpload.name,
            fileSize: fileToUpload.size,
            fileType: fileToUpload.type,
            hasOriginFileObj: !!file.originFileObj,
            fileSource: file.originFileObj ? 'originFileObj' : (file instanceof File ? 'file' : 'DOM')
        });

        setUploading(true);
        setUploadProgress(0);
        setError(null);
        setSuccess(null);

        const reader = new FileReader();
        reader.readAsDataURL(fileToUpload);
        reader.onload = async () => {
            const base64Image = reader.result as string;
            const token = localStorage.getItem('authToken');

            try {
                // 模拟上传进度
                setUploadProgress(30);

                const response = await axios.post(
                    '/api/faces/register/',
                    { image: base64Image },
                    {
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Token ${token}`,
                        },
                        onUploadProgress: (progressEvent) => {
                            if (progressEvent.total) {
                                const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                                setUploadProgress(Math.min(progress, 90)); // 最多显示90%，留10%给处理
                            }
                        }
                    }
                );

                setUploadProgress(100);

                if (response.status === 200 || response.status === 201) {
                    const isUpdate = response.status === 200;
                    const successMsg = isUpdate ? '人脸数据更新成功！' : '人脸数据注册成功！';
                    setSuccess(successMsg);
                    message.success(successMsg);

                    console.log('人脸数据操作成功:', {
                        operation: isUpdate ? 'update' : 'create',
                        userId: response.data.user,
                        timestamp: response.data.updated_at || response.data.created_at
                    });

                    // 立即更新当前人脸数据状态
                    setCurrentFaceData(response.data);
                    console.log('立即更新人脸数据状态:', response.data);

                    // 重新获取人脸数据以确保UI状态同步（延迟执行避免竞态条件）
                    setTimeout(async () => {
                        console.log('延迟刷新人脸数据...');
                        await fetchCurrentFaceData();
                    }, 500);

                    // 清除上传状态
                    setTimeout(() => {
                        setFileList([]);
                        setPreviewImage(null);
                        setUploadProgress(0);
                        setSuccess(null); // 清除成功消息
                    }, 2000); // 延长显示时间让用户看到成功消息
                }
            } catch (err: any) {
                const errorMessage = err.response?.data?.error || '上传失败，请稍后重试。';
                setError(errorMessage);
                message.error(errorMessage);
                setUploadProgress(0);
            } finally {
                setUploading(false);
            }
        };

        reader.onerror = () => {
            setError('读取文件失败。');
            message.error('读取文件失败。');
            setUploading(false);
            setUploadProgress(0);
        };
    };

    const props: UploadProps = {
        onRemove: (file) => {
            const index = fileList.indexOf(file);
            const newFileList = fileList.slice();
            newFileList.splice(index, 1);
            setFileList(newFileList);
            setPreviewImage(null);
            setError(null);
            setSuccess(null);
        },
        beforeUpload: (file) => {
            const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
            if (!isJpgOrPng) {
                message.error('你只能上传 JPG/PNG 格式的图片!');
                return false;
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                message.error('图片大小必须小于 2MB!');
                return false;
            }

            // 创建预览图片
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => {
                setPreviewImage(reader.result as string);
            };

            setFileList([file]); // Replace file list with the new file
            setError(null);
            setSuccess(null);

            return false; // Prevent auto-upload
        },
        fileList,
        listType: "picture-card",
        maxCount: 1,
        showUploadList: false, // 我们将自定义显示
    };

    return (
        <div style={{ maxWidth: 800, margin: '2rem auto', padding: '0 1rem' }}>
            <Card title={<Title level={2}><UserOutlined /> 人脸数据管理</Title>}>
                <Text type="secondary" style={{ display: 'block', marginBottom: '1.5rem' }}>
                    请上传一张清晰、无遮挡的正面照片用于门禁识别。系统将提取你的面部特征信息。
                    {currentFaceData && '如果已有数据，本次上传将覆盖原有数据。'}
                </Text>

                {/* 当前人脸数据状态 */}
                {currentFaceData && (
                    <Alert
                        message="已注册人脸数据"
                        description={
                            <div>
                                <div>注册时间: {new Date(currentFaceData.created_at).toLocaleString('zh-CN')}</div>
                                {currentFaceData.updated_at && currentFaceData.updated_at !== currentFaceData.created_at && (
                                    <div>更新时间: {new Date(currentFaceData.updated_at).toLocaleString('zh-CN')}</div>
                                )}
                                <div style={{ fontSize: '12px', color: '#666', marginTop: '4px' }}>
                                    数据ID: {currentFaceData.id}
                                </div>
                            </div>
                        }
                        type="info"
                        showIcon
                        style={{ marginBottom: '1.5rem' }}
                    />
                )}

                {!currentFaceData && !loading && (
                    <Alert
                        message="尚未注册人脸数据"
                        description="请上传一张人脸照片以启用人脸识别功能"
                        type="warning"
                        showIcon
                        style={{ marginBottom: '1.5rem' }}
                    />
                )}

                <div style={{ display: 'flex', gap: '2rem', alignItems: 'flex-start' }}>
                    {/* 上传区域 */}
                    <div style={{ flex: 1 }}>
                        <Dragger {...props} style={{ marginBottom: '1rem' }}>
                            <p className="ant-upload-drag-icon">
                                <InboxOutlined />
                            </p>
                            <p className="ant-upload-text">点击或拖拽图片到此区域</p>
                            <p className="ant-upload-hint">
                                支持 JPG/PNG 格式，大小不超过 2MB
                            </p>
                        </Dragger>

                        {/* 上传进度 */}
                        {uploading && uploadProgress > 0 && (
                            <div style={{ marginBottom: '1rem' }}>
                                <Progress
                                    percent={uploadProgress}
                                    status={uploadProgress === 100 ? 'success' : 'active'}
                                    strokeColor={{
                                        '0%': '#108ee9',
                                        '100%': '#87d068',
                                    }}
                                />
                                <Text type="secondary" style={{ fontSize: '12px' }}>
                                    {uploadProgress < 90 ? '正在上传...' : '正在处理人脸数据...'}
                                </Text>
                            </div>
                        )}

                        {/* 操作按钮 */}
                        <Space style={{ width: '100%' }} direction="vertical">
                            <Button
                                type="primary"
                                onClick={handleUpload}
                                disabled={fileList.length === 0 || uploading}
                                loading={uploading}
                                style={{ width: '100%' }}
                                icon={<UploadOutlined />}
                                size="large"
                            >
                                {uploading ? '正在处理...' : (currentFaceData ? '更新人脸数据' : '注册人脸数据')}
                            </Button>

                            {fileList.length > 0 && (
                                <Button
                                    onClick={clearPreview}
                                    disabled={uploading}
                                    style={{ width: '100%' }}
                                    icon={<DeleteOutlined />}
                                >
                                    清除选择
                                </Button>
                            )}
                        </Space>
                    </div>

                    {/* 预览区域 */}
                    {previewImage && (
                        <div style={{ flex: 1, maxWidth: '300px' }}>
                            <Divider orientation="left">图片预览</Divider>
                            <div style={{
                                border: '2px dashed #d9d9d9',
                                borderRadius: '8px',
                                padding: '1rem',
                                textAlign: 'center',
                                backgroundColor: '#fafafa'
                            }}>
                                <Image
                                    src={previewImage}
                                    alt="预览图片"
                                    style={{
                                        maxWidth: '100%',
                                        maxHeight: '300px',
                                        borderRadius: '4px'
                                    }}
                                    preview={{
                                        mask: <div><EyeOutlined /> 查看大图</div>
                                    }}
                                />
                                <div style={{ marginTop: '0.5rem' }}>
                                    <Text type="secondary" style={{ fontSize: '12px' }}>
                                        {fileList[0]?.name}
                                    </Text>
                                </div>
                            </div>
                        </div>
                    )}
                </div>

                {/* 状态消息 */}
                {error && (
                    <Alert
                        message="上传失败"
                        description={error}
                        type="error"
                        showIcon
                        style={{ marginTop: '1rem' }}
                        closable
                        onClose={() => setError(null)}
                    />
                )}

                {success && (
                    <Alert
                        message="操作成功"
                        description={success}
                        type="success"
                        showIcon
                        style={{ marginTop: '1rem' }}
                        closable
                        onClose={() => setSuccess(null)}
                    />
                )}
            </Card>
        </div>
    );
};

export default FaceManagementPage;